<template>
  <!-- 上传图片 -->
  <el-dialog
    class="upload-img-dialog"
    title="上传图片"
    :visible.sync="showDialog"
    width="50%"
    :before-close="handleClose"
  >
    <div class="flex align-top justify-center">
      <div class="flex-sub">
        <el-upload
          ref="upload"
          multiple
          drag
          action="#"
          :on-change="onChange"
          :file-list="fileList"
          :auto-upload="false"
          :http-request="uploadFn"
          :on-remove="handleRemove"
        >
          <div v-if="!previewUrl">
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </div>
          <el-image v-else :src="previewUrl" fit="scale-down" />
          <div slot="tip" class="el-upload__tip">
            <span class="text-red">文件名称需与SKU名称一致</span
            >只能上传jpg/png文件，且不超过50MB
          </div>
        </el-upload>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="uploadFn">上 传</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { untransform } from "@/store/yg/common/uri";
import * as constant from "@/store/yg/common/constant";
import { m } from "@/store/yg/common/local";

export default {
  props: {
    showUploadImg: {
      type: Boolean,
      default: false
    },
    fnName: {
      type: String,
      default: "#"
    },
    waybillId: {
      type: String,
      default: "#"
    },
    url: {
      type: String,
      default: "#"
    }
  },
  created: function() {
    this.action =
      constant.API_SERVER +
      "/api/consume/upload?uri=" +
      untransform(this.$route.params.uri) +
      "&f=" +
      this.fnName +
      "&type=blank";
  },
  data() {
    return {
      action: "",
      fileList: [],
      previewUrl: ""
    };
  },
  computed: {
    showDialog: {
      get: function() {
        return this.showUploadImg;
      },
      set: function(val) {
        this.$emit(`update:showUploadImg`, val);
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.closeFn();
        })
        .catch(_ => {});
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      if (fileList.length === 0) {
        this.previewUrl = "";
      }
    },
    handlePreview(file) {
      console.log("handlePreview", file);
    },
    onChange(file, fileList) {
      this.fileList = fileList;
      this.previewUrl = URL.createObjectURL(file.raw);
      console.log(
        "%cthis.ruleForm.coverFile: ",
        "color: MidnightBlue; background: Aquamarine;",
        this.previewUrl
      );
    },

    beforeUpload(file) {
      console.log("beforeUpload");

      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      if (!isJPG && !isPng) {
        this.$message.error("上传文件只能是jpg/png文件!");
        return false;
      }
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 1MB!");
        return false;
      }
      return true;
    },

    closeFn() {
      this.fileList = [];
      this.previewUrl = "";
      const rule = {
        coverFile: "",
        coverUrl: ""
      };
      this.$emit(`update:ruleForm`, rule);
      this.$emit(`update:showUploadImg`, false);
    },

    async uploadFn(params) {
      // 通过 FormData 对象上传文件
      // var formData = new FormData();
      // formData.append("items[]", params.file);
      if (this.fileList.length === 0) {
        this.$message.error("请上传文件");
        return false;
      }

      this.$store.dispatch("app/toggleDialog", true);
      // 通过 FormData 对象上传文件
      const formData = new FormData();
      // 通过 FormData 对象上传文件
      for (const i of this.fileList) {
        if (await this.beforeUpload(i.raw)) {
          formData.append("items[]", i.raw);
        }
      }
      formData.append("waybillId", this.waybillId);

      axios({
        method: "post",
        url: this.action,
        data: formData
      })
        .then(res => {
          console.log(res);
          if (res.data.errorMesage != null) {
            this.$notify.error({
              title: "错误",
              message: "上传失败!" + res.data.errorMesage
            });
          } else {
            this.$emit(`getImgUrl`, res.data.data);
            this.previewUrl = "";
            this.$emit(`update:showUploadImg`, false);
            this.fileList = [];
          }
        })
        .catch(error => {
          console.log(error);
          this.$notify.error({
            title: "错误",
            message: "上传失败!"
          });
        });
    }
  }
};
</script>

<style lang="scss">
.upload-img-dialog {
  .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
  .upload-img {
    height: calc(100% - 46px);
    .el-upload {
      width: 100%;
      height: 100%;
      .el-upload-dragger {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>

<style scoped>
/deep/.el-upload-dragger {
  height: auto;
  min-height: 180px;
  max-height: 500px;
}
</style>
